package store

import (
	"gorm.io/gorm"
	"gorm.io/gorm/clause"
)

type (
	ApiStore struct {
		db *gorm.DB
	}

	DirectoryEntity struct {
		Id            int    `gorm:"primaryKey;autoIncrement;"`
		DirectoryId   string `gorm:"column:directory_id;type:text not null;comment:目录ID;"`
		DirectoryName string `gorm:"column:directory_name;type:text not null;comment:目录名称"`
		ParentId      int    `gorm:"column:parent_id;"`
	}

	InstanceEntity struct {
		Id           int    `gorm:"primaryKey;autoIncrement;"`
		InstanceId   string `gorm:"column:instance_id;type:text"`
		InstanceName string `gorm:"column:instance_name;type:text not null"`
		DirectoryId  string `gorm:"column:directory_id;type:text not null"`
		RequestInfo  string `gorm:"column:request_info;type:text not null"`
	}
)

func (d DirectoryEntity) TableName() string {
	return "tbl_directory_info"
}

func (i InstanceEntity) TableName() string {
	return "tbl_instance_info"
}

func (store *ApiStore) DirectoryIndex() int {
	var entity DirectoryEntity
	store.db.Model(&DirectoryEntity{}).Order("id desc").First(&entity)
	return entity.Id + 1
}

func (store *ApiStore) InstanceIndex() int {
	var entity InstanceEntity
	store.db.Model(&InstanceEntity{}).Order("id desc").First(&entity)
	return entity.Id + 1
}

func (store *ApiStore) SaveOrUpdateDirectory(entity DirectoryEntity) {
	store.db.Clauses(clause.OnConflict{
		Columns:   []clause.Column{{Name: "id"}},
		DoUpdates: clause.Assignments(map[string]interface{}{"directory_name": entity.DirectoryName, "parent_id": entity.ParentId}),
	}).Create(&entity)
}

func (store *ApiStore) SaveOrUpdateInstance(entity InstanceEntity) {
	store.db.Clauses(clause.OnConflict{
		Columns:   []clause.Column{{Name: "id"}},
		DoUpdates: clause.Assignments(map[string]interface{}{"instance_name": entity.InstanceName, "directory_id": entity.DirectoryId, "request_info": entity.RequestInfo}),
	}).Create(&entity)

}

func (store *ApiStore) DeleteDirectory(directoryId int) {
	store.db.Where("directory_id = ?", directoryId).Delete(&DirectoryEntity{})
	store.db.Where("directory_id = ?", directoryId).Delete(&InstanceEntity{})
}

func (store *ApiStore) DeleteInstance(instanceId int) {
	store.db.Where("instance_id = ?", instanceId).Delete(&InstanceEntity{})
}

func (store *ApiStore) GetDirectoryList() []DirectoryEntity {
	var list []DirectoryEntity
	store.db.Find(&list)
	return list
}

func (store *ApiStore) GetInstanceList() []InstanceEntity {
	var list []InstanceEntity
	store.db.Find(&list)
	return list
}
